package com.wave.gate.mqtt.client;



import cn.hutool.core.date.DateUtil;
import com.wave.gate.domain.PassRecord;
import com.wave.gate.mqtt.config.MqttProperties;
import com.wave.gate.service.IPassRecordService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class MqttSendClient {


    @Autowired
    private MqttSendCallBack mqttSendCallBack;

    @Autowired
    private MqttProperties mqttProperties;

    @Autowired
    IPassRecordService passRecordService;

    public static MqttClient mqttSendClient;

    public static MqttClient getMqttSendClient() {
        return mqttSendClient;
    }

    public static void setMqttSendClient(MqttClient mqttSendClient) {
        MqttSendClient.mqttSendClient = mqttSendClient;
    }

    public MqttClient connect() {
        MqttClient client = null;
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            client = new MqttClient(mqttProperties.getHostUrl(),uuid , new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(mqttProperties.getUsername());
            options.setPassword(mqttProperties.getPassword().toCharArray());
            options.setConnectionTimeout(mqttProperties.getTimeout());
            options.setKeepAliveInterval(mqttProperties.getKeepAlive());
            options.setCleanSession(true);
            options.setAutomaticReconnect(false);
            try {
                // 设置回调
                client.setCallback(mqttSendCallBack);
                client.connect(options);
                MqttSendClient.setMqttSendClient(client);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 发布消息
     * 主题格式： $orgCode(参数实际使用机构代码)
     *
     * @param retained    是否保留
     * @param topic     主题
     * @param pushMessage 消息体
     */
    public void publish(boolean retained, String topic, String pushMessage) {
        MqttMessage message = new MqttMessage();
        message.setQos(mqttProperties.getQos());
        message.setRetained(retained);
        message.setPayload(pushMessage.getBytes());
        MqttDeliveryToken token;
        MqttClient mqttClient = connect();
        try {
            mqttClient.publish(topic, message);
        } catch (MqttException e) {
            log.error("mqtt消息发送异常，保存在本地sqlite数据库");
            PassRecord record = new PassRecord();
            record.setPassRecordJson(pushMessage);
            record.setCreateTime(DateUtil.formatDateTime(new Date()));
            passRecordService.save(record);
            e.printStackTrace();
        } finally {
            disconnect(mqttClient);
            //close(mqttClient);
        }
    }

    /**
     * 关闭连接
     *
     * @param mqttClient
     */
    public static void disconnect(MqttClient mqttClient) {
        try {
            if (mqttClient != null) {
                log.info("mqtt断开连接,clientId：{}", mqttClient.getClientId());
                mqttClient.disconnect();
                mqttClient.close();
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @param mqttClient
     */
    public static void close(MqttClient mqttClient) {
        try {
            if (mqttClient != null) {
                log.info("mqtt关闭连接,clientId：{}", mqttClient.getClientId());
                mqttClient.close();
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

